Tell me when we will use ViewBag in asp.net MVC with the help of suitable example.
When to use ViewBag in asp.net MVC?
294
28-Jan-2020
Updated on 28-Jan-2020
Nishi Tiwari
28-Jan-2020ViewBag is used to allow us to share values dynamically. There are several variables which are not known by us before the program is run, and these values are entered only during the runtime. And this is where ViewBag shines, because we can put just about anything which we want in ViewBag.
We can use ViewBag objects for small amounts of data which are transferring it from the controller to the view. It will work well for all such cases as:
• Shopping carts
• Dropdown lists options
• Widgets
• Aggregated data
It is a great way to access data which we use but may reside outside the data model. It is also easy to use because it is implemented as a property of both controllers and view.
There is also one place when ViewBag is mandatory, and that is when we are specifying a page title on any given view. For example: